import { Component, ViewChild, Injector, Output, EventEmitter, ElementRef } from '@angular/core';
import { ModalDirective } from 'ngx-bootstrap';
import { PhoneNumberEditDto, PersonServiceProxy } from '@shared/service-proxies/service-proxies';
import { AppComponentBase } from '@shared/app-component-base';
import { finalize } from 'rxjs/operators';

@Component({
  selector: 'app-phone-number',
  templateUrl: './phone-number.component.html'
})
export class PhoneNumberComponent extends AppComponentBase {

  @ViewChild('phoneNumberModal') modal: ModalDirective;
  @ViewChild('modalContent') modalContent: ElementRef;

  @Output() modalSave: EventEmitter<any> = new EventEmitter<any>();

  active: boolean = false;
  saving: boolean = false;

  phoneNumber: PhoneNumberEditDto = null;

  constructor(
    injector: Injector,
    private _personService: PersonServiceProxy
  ) {
    super(injector);
  }

  show(pid: number, phoneNumber?: PhoneNumberEditDto): void {
    if (phoneNumber) {
      this.phoneNumber = phoneNumber;
    } else {
      this.phoneNumber = new PhoneNumberEditDto();
      this.phoneNumber.type = 1; //设置默认选择项
      this.phoneNumber.personId = pid;
    }
    this.active = true;
    this.modal.show();
  }

  onShown(): void {
    $.AdminBSB.input.activate($(this.modalContent.nativeElement));
  }

  save(): void {
    //TODO: 将添加和修改电话号码放在同一个模态框里。
    this.saving = true;
    this._personService.addPhoneNumberAsync(this.phoneNumber)
      .pipe(finalize(() => { this.saving = false; }))
      .subscribe(() => {
        this.notify.info(this.l('SavedSuccessfully'));
        this.close();
        this.modalSave.emit(null);
      });
  }

  close(): void {
    this.active = false;
    this.modal.hide();
  }
}
